import { createContext, useContext } from "solid-js";
import { useSourceCodeStore } from "./Editor/useSourceCodeStore";
import { TextEditorComp } from "./Editor/TextEditor";
import { atom } from "@cn-ui/use";
import { FileExplorer } from "./FileExplorer/FileExplorer";
import { LocalIframeRuntimeComp } from "./Runtime/Envs/LocalIframeRuntimeComp";
import { RollupWebRuntime } from "./Runtime/RollupWebRuntime";
import { WorkerRuntimeComp } from "./Runtime/Envs/WorkerRuntimeComp";
import { BlocklyComp } from "./Editor/Blockly";
export const CodingSystemContext = createContext<
    ReturnType<typeof useSourceCodeStore> & ReturnType<typeof useSystemValue>
>();

export const useSystemValue = () => {
    return {
        explorerVisible: atom(false),
        editorOpenFile: atom((code: string) => undefined),
        runtime: atom<RollupWebRuntime>(null),
    };
};
export const CodingApp = () => {
    return (
        <CodingSystemContext.Provider
            value={{
                ...useSourceCodeStore({
                    async loadCodeFromRemote() {
                        const getString = (str: string) =>
                            fetch(str).then((res) => res.text());
                        const index = await getString("./test.html");
                        const compiler = await getString("./iframe.js");
                        const test = await getString("./test.js");
                        return [
                            ["/index.html", index],
                            ["/.web.compiler.js", compiler],
                            ["/test/index.test.js", test],
                        ];
                    },
                }),
                ...useSystemValue(),
            }}
        >
            <section class="h-screen flex w-full  relative  select-none bg-neutral-50">
                <div class="h-full w-full flex bg-white flex-1">
                    <FileExplorer></FileExplorer>
                    <TextEditorComp></TextEditorComp>
                    {/* <BlocklyComp></BlocklyComp> */}
                </div>
                <Previewer></Previewer>
            </section>
        </CodingSystemContext.Provider>
    );
};
export const Previewer = () => {
    const { runtime } = useContext(CodingSystemContext);
    return (
        <div class="w-full max-w-sm h-full bg-neutral-100 flex flex-col ">
            <div class="h-8 ">
                <button
                    onclick={() => {
                        runtime().reload();
                    }}
                >
                    重新加载
                </button>
            </div>
            {/* <LocalIframeRuntimeComp></LocalIframeRuntimeComp> */}
            <WorkerRuntimeComp></WorkerRuntimeComp>
        </div>
    );
};
